package com.lepu.app.main.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.app.config.UserConfig;
import com.app.utils.AppEnterTongJi;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.chat.activity.OnlineActivity;
import com.lepu.app.fun.chat.business.uiflow.UITransition;
import com.lepu.app.fun.chat.controller.base.AbsBaseFragment;
import com.lepu.app.fun.chat.util.BadgeView;
import com.lepu.app.fun.hospital.HospitalAdviceReportActivity;
import com.lepu.app.fun.hospital.HospitalConsultActivity;
import com.lepu.app.fun.hospital.HospitalConsultMainActivity;
import com.lepu.app.fun.hospital.HospitalLectureActivity;
import com.lepu.app.fun.hospital.adapter.HospitalShowAdapter;
import com.lepu.app.fun.hospital.bean.Hospital;
import com.lepu.app.fun.hospital.bean.HospitalShow;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.FocusView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@SuppressLint("InflateParams")
public class MainTabFragmentHospital extends AbsBaseFragment implements
		AsyncRequest, CustomTopBarNew.OnTopbarNewRightButtonListener,
		View.OnClickListener, com.core.lib.utils.Observer, OnRefreshListener {

	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_NEW_COUNT = "request_NEW_COUNT";
	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_COUNT_SUCCESS = 12;
	private static final int MSG_COUNT_FAIL = 13;

	private View mMainView = null;
	private boolean mInitDataSuccess = false;// 是否加载完数据

	private LinearLayout mFocusLayout;
	private ListView mListView;
	private BadgeView mTxtviewTips;
	private FocusView mFocusView = null;
	private HospitalShowAdapter mAdapter;
	private SwipeRefreshLayout mRefreshLayout = null;
	private View mHeaderView = null;

	public boolean mRefreshFlag = true;

	public int mKidGold = 0;
	public int mWomanGold = 0;
	@SuppressLint("InflateParams")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mMainView = LayoutInflater.from(getActivity()).inflate(
				R.layout.main_tab_fragment_hospital, null, false);
		init();
	}

	@Override
	public void onResume() {
		super.onResume();

		if (mFocusView != null) {
			mFocusView.onResumeViewPager();
		}

		UmengHelper.OnPageStart("22");
		
		changeTip();
		requestNewCount();
	}

	@Override
	public void onPause() {
		super.onPause();

		if (mFocusView != null) {
			mFocusView.onPauseViewPager();
		}

		UmengHelper.OnPageEnd("22");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		ViewGroup p = (ViewGroup) mMainView.getParent();
		if (p != null) {
			p.removeAllViewsInLayout();
		}
		return mMainView;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		mInitDataSuccess = false;
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);

		if (isVisibleToUser) {
			if (!mInitDataSuccess || mRefreshFlag) {
				// 第一次进入页面获取数据
				mRefreshFlag = false;
				// 第一次进入页面获取数据
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						mRefreshLayout.setRefreshing(true);  //直接调用是没有用的
					}
				}, 100);
				request();
			}
		}
	}

	/*
	 * 初始化ui控件，不要初始化数据！！！！
	 * 
	 * 初始化控件，需要用mMainView.findViewById 不能使用findViewById，否则程序会闪退的
	 */
	@SuppressWarnings("deprecation")
	private void init() {

		mRefreshLayout = (SwipeRefreshLayout) mMainView
				.findViewById(R.id.swipeLayout);
		mRefreshLayout.setOnRefreshListener(this);
		mRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
				R.color.color_listview_refresh_2,
				R.color.color_listview_refresh_3,
				R.color.color_listview_refresh_4);

		mListView = (ListView) mMainView.findViewById(R.id.two_listview);

		TextView mTextViewChatSession = (TextView) mMainView
				.findViewById(R.id.txtview_chatsession);
		TextView mTextViewTitle = (TextView) mMainView
				.findViewById(R.id.topbarTitleTextView);
		mTextViewTitle.setText(R.string.main_menu_hospital);
		mTextViewChatSession.setText(R.string.chat_zixun_record);
		mTextViewChatSession.setOnClickListener(this);

		mTxtviewTips = (BadgeView) mMainView.findViewById(R.id.textview_tips);
		mTxtviewTips
				.setTextColor(getResources().getColor(R.color.colortipsred));

		//======================================================
		mHeaderView = LayoutInflater.from(getActivity()).inflate(R.layout.main_tab_fragment_hospital_header,null);

		mFocusLayout = (LinearLayout) mHeaderView.findViewById(R.id.two_focus_layout);
		
		LinearLayout layout_search = (LinearLayout) mHeaderView.findViewById(R.id.layout_search);
		LinearLayout layout_kid = (LinearLayout) mHeaderView.findViewById(R.id.layout_kid);
		LinearLayout layout_woman = (LinearLayout) mHeaderView.findViewById(R.id.layout_woman);

		layout_search.setOnClickListener(mViewClickListener);
		layout_kid.setOnClickListener(mViewClickListener);
		layout_woman.setOnClickListener(mViewClickListener);
		

		mAdapter = new HospitalShowAdapter(getActivity(), HospitalShow.getDataList());
		mListView.addHeaderView(mHeaderView);
		mListView.setAdapter(mAdapter);

		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,int i, long l) {

				if (i == 1) {  //常见问题
					AppEnterTongJi.clickEvent(55, "");
					
					Intent intent = new Intent(getActivity(),HospitalConsultActivity.class);
					MainTabActivity.getInstance().startActivity(intent, true);
				}else if(i == 2){  //健康讲座
					AppEnterTongJi.clickEvent(54, "");
					
					MainTabActivity.getInstance().startActivity(new Intent(getActivity(),HospitalLectureActivity.class), true);
				}else if(i == 3){  //电话
					AppEnterTongJi.clickEvent(57, "");
					
					if (MainTabActivity.jumpLogin(MainTabActivity.getInstance())) {
						return;
					}
					tell();
				}
				
			}
		});

		ObserverManager.getInstance().addObserver(ObserverConst.NOTIFY_ZXRECORDER_CHANGE, this);
	}


	View.OnClickListener mViewClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.layout_kid:
				boolean flag1 = LoginUtil.jumpLogin((BaseFragmentActivity)getActivity());
				if (flag1) {
					return;
				}

				Intent intent1 = new Intent(getActivity(), OnlineActivity.class);
				intent1.putExtra("ConsultPrice", mKidGold);
				intent1.putExtra("type", 2);
				getActivity().startActivity(intent1);
				UITransition.setActivityStartRightIn((FragmentActivity) getActivity());
				break;
			case R.id.layout_woman:
				boolean flag2 = LoginUtil.jumpLogin((BaseFragmentActivity)getActivity());
				if (flag2 ) {
					return;
				}

				Intent intent2 = new Intent(getActivity(), OnlineActivity.class);
				intent2.putExtra("ConsultPrice", mWomanGold);
				intent2.putExtra("type", 1);
				getActivity().startActivity(intent2);
				UITransition.setActivityStartRightIn((FragmentActivity) getActivity());
				break;
			case R.id.layout_search:
				AppEnterTongJi.clickEvent(56, "");
																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																																	
				Intent intentConsult = new Intent(getActivity(),
						HospitalConsultMainActivity.class);
				MainTabActivity.getInstance()
						.startActivity(intentConsult, true);
				break;
			default:
				break;
			}
		}
	};

	public void request() {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			String version = getActivity().getPackageManager().getPackageInfo(
					getActivity().getPackageName(), 0).versionName;
			params.put("ClientVersion", version);

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getHospitalUrl(), map, null, this,REQUEST_DATA, true, false, true);
	}

	public void requestNewCount(){
		
		if(!LoginUtil.checkIsLogin()){
			return;
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			params.put("MaxTime", UserConfig.getConfigString(getActivity(), "MaxTime", ""));

		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(Setting.getHospitalNewCountUrl(), map, null, this,REQUEST_NEW_COUNT, true, false);
	}
	
	private void tell() {
		new MyDialog(getActivity())
				.setMessage(
						"电话咨询服务时间：周一至周日，每天8:30-17:00；费用：我们不收取任何费用，你只需支付普通市话费即可。")
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

							}
						})
				.setPositiveButton(R.string.app_zixun,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

								String phone = getString(R.string.usercenter_phone);
								UtilityBase.callPhone( phone);
							}
						}).create(null).show();
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if(getActivity() == null)
			{
				return;
			}
			switch (msg.what) {
			case MSG_DATA_SUCCESS:
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						mRefreshLayout.setRefreshing(false);
					}
				}, 100);
				
				Hospital hospital = (Hospital) msg.obj;
				if (hospital != null) {
					// 轮播图
					if (hospital.Banner != null && hospital.Banner.size() > 0) {

						mFocusView = new FocusView(getActivity(),
								hospital.Banner,
								Utils.getBannerHeight25To8(getActivity()),
								null, 0,R.drawable.index_banner_icon_default,mRefreshLayout);
						mFocusLayout.removeAllViews();
						mFocusLayout.addView(mFocusView);
						mFocusLayout.setVisibility(View.VISIBLE);
					} else {
						mFocusLayout.setVisibility(View.GONE);
					}
					
				} else {
					UIHelper.showToast(getActivity(), R.string.no_data);
				}
				break;
			case MSG_DATA_FAIL:
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						mRefreshLayout.setRefreshing(false);
					}
				}, 100);
				break;
			case MSG_COUNT_SUCCESS:
				
				changeTip();
				
				break;
			case MSG_COUNT_FAIL:
				break;
				
			default:
				break;
			}
		}

		;
	};


	@SuppressWarnings("rawtypes")
	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			// 解析json data
			Hospital dataArray = Hospital.parseJsonData((String) data);
			
			if(!TextUtils.isEmpty(dataArray.PediatricsCredits)){
				mKidGold = Integer.valueOf(dataArray.PediatricsCredits);
			}
			
			if(!TextUtils.isEmpty(dataArray.ObstetricsGynecologyCredits)){
				mWomanGold = Integer.valueOf(dataArray.ObstetricsGynecologyCredits);
			}
			
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArray;
			mHandler.sendMessage(msg);
			mInitDataSuccess = true;
		}else if(object.equals(REQUEST_NEW_COUNT)){
			
			try {
				JSONObject jsonObject = new JSONObject((String)data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject obj2 = (JSONObject) obj1.get("DetailInfo");
				
			    Iterator it = obj2.keys();  
			      
		        while (it.hasNext()) {  
		  
		            String key = it.next().toString();  
		            String value = obj2.getString(key);
   		            
		            if(key.equals("NewCount")){
		            	int beforeCount = Integer.valueOf(UserConfig.getConfigString(getActivity(), "NewCount", "0"));
		            	int thisCount = Integer.valueOf(value);
		            	int count = beforeCount + thisCount;
		            	
		            	UserConfig.setConfig(getActivity(), "NewCount", String.valueOf(count));
		            }else if(key.equals("MaxTime")){
		            	int thisCount = 0;
		            	
		            	if(!TextUtils.isEmpty(obj2.getString("NewCount"))){
		            		thisCount = Integer.valueOf(obj2.getString("NewCount"));
		            	}
		            	
		            	if(thisCount > 0){
		            		UserConfig.setConfig(getActivity(), "MaxTime", value);
		            	}
		            	
		            }else{
		            	int beforeCount = Integer.valueOf(UserConfig.getConfigString(getActivity(), key, "0"));
		            	int thisCount = Integer.valueOf(value);
		            	int count = beforeCount + thisCount;
		            	
		            	UserConfig.setConfig(getActivity(), key, String.valueOf(count));
		            }
		           
		        } 
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			Message msg = mHandler.obtainMessage();
			msg.what = MSG_COUNT_SUCCESS;
			mHandler.sendMessage(msg);
			
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		}else if(object.equals(REQUEST_NEW_COUNT)){
			mHandler.sendEmptyMessage(MSG_COUNT_FAIL);
		}
	}

	@Override
	public void onTopbarRightButtonSelected() {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.txtview_chatsession:
			if (LoginUtil.checkIsLogin()) {
				// 咨询记录
				AppEnterTongJi.clickEvent(53, "");
				//performGoAction("gotoChatSessionFragment", null);
				Intent intent = new Intent(getActivity(), HospitalAdviceReportActivity.class);
				MainTabActivity.getInstance().startActivity(intent, true);
			} else {
				LoginUtil.jumpLogin(MainTabActivity.getInstance());
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void notify(String s, Object o, final Object o1) {
		
	}

	private void changeTip() {
		if(!LoginUtil.checkIsLogin()){
			return;
		}
		
		int count = Integer.valueOf(UserConfig.getConfigString(getActivity(), "NewCount", "0"));
		
		if (count > 0 && mTxtviewTips != null){
			mTxtviewTips.setVisibility(View.VISIBLE);
			mTxtviewTips.setText(String.valueOf(count));
		}else{
			mTxtviewTips.setVisibility(View.GONE);
		}
			
	}

	@Override
	public void onRefresh() {
		request();
	}

}
